import { BaseModel } from './BaseModel.js';
import { dataFiles } from '../config/database.js';

// 默认用户角色关联
// user id 1 (admin) -> role admin (1)
// user id 2 (teacher1) -> role teacher (2)
// user id 3 (student1) -> role student (3)

const defaultUserRoles = [
    { id: 1, userId: 1, roleId: 1, createdAt: new Date().toISOString() }, // admin用户 -> 超级管理员角色
    { id: 2, userId: 2, roleId: 2, createdAt: new Date().toISOString() }, // teacher1 -> 教师角色
    { id: 3, userId: 3, roleId: 3, createdAt: new Date().toISOString() }, // student1 -> 学生角色
];

export class UserRole extends BaseModel {
    constructor() {
        super(dataFiles.userRoles, defaultUserRoles);
    }

    findByUserId(userId) {
        return this.findAll().filter(ur => ur.userId === userId);
    }

    findByRoleId(roleId) {
        return this.findAll().filter(ur => ur.roleId === roleId);
    }

    getUserRoles(userId) {
        return this.findByUserId(userId);
    }

    addUserRole(userId, roleId) {
        const existing = this.findOne({ userId, roleId });
        if (existing) {
            return existing;
        }
        return this.create({ userId, roleId });
    }

    removeUserRole(userId, roleId) {
        const item = this.findOne({ userId, roleId });
        if (item) {
            return this.delete(item.id);
        }
        return false;
    }

    removeAllUserRoles(userId) {
        const userRoles = this.findByUserId(userId);
        userRoles.forEach(ur => this.delete(ur.id));
        return true;
    }
}

